/*
* @Date: 2021/2/24
* @Author: XueChengwu <xuechengwu@erayt.com>
* @Copyright: 2015-2019 Erayt, Inc.
* @Description: If you have some questions, please contact: xuechengwu@erayt.com.
*/
import get from '../utils/get';
import redis from "../server/core/db/redis";
import rabbitmq from "../server/core/rabbitmq";
const CronJob = require('cron').CronJob;
let lastId = 0;
async function main() {
  const channel = await rabbitmq.getChannel();
  channel.assertExchange('quotation', 'direct', { durable: false });
  new CronJob('*/5 * * * * *', function () {
    get('https://www.jin10.com/flash_newest.js', {})
      .then( async (response) => {
        const res = response.text;
        const resTrim = res.replace(/var\s*newest\s*=/, '').trim();
        const newsData = JSON.parse(resTrim.substr(0, resTrim.length - 1));

        const results = [];
        for (let i = 0; i < newsData.length;i++) {
          if (newsData[i].id === lastId) {
            break;
          }
          if (!newsData[i].data || !newsData[i].data.content) {
            continue;
          }
          if (/<a\s*[^>]*><img\s*[^]*><\/a>/.test(newsData[i].data.content)) {
            continue;
          }
          if (newsData[i].data.content.indexOf('<b>') >= 0) {
            newsData[i].data.bold = true;
            newsData[i].data.content = newsData[i].data.content.replace('<br>', '').replace('</br>', '');
          }
          results.push(newsData[i]);
        }
        lastId = newsData[0].id;
        if (results.length > 0) {

          try {
            console.log('result===>');
            channel.publish('quotation', 'info', Buffer.from(`JIN10_NEWS_PUSH:${JSON.stringify(results)}`));
          } catch(error) {
            console.error(error.toString());
          }
        }
      }).catch(err => {
      console.log('err===>', err);
    });
  }, null, true);
}
main();

